package com.xiaodong.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaodong.reggie.currency.R;
import com.xiaodong.reggie.dto.UserDto;
import com.xiaodong.reggie.entity.Employee;
import com.xiaodong.reggie.entity.User;
import com.xiaodong.reggie.service.UserService;
import com.xiaodong.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserContorller {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //验证码发送
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();

        //生成验证码
        if (!StringUtils.isEmpty(phone)) {

            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码是=={}", code);

            //将生成的验证码上传到session里面
            //session.setAttribute(phone, code);

            //将生成的验证码保存到redis当中并设置有效时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.success("手机验证码发送成功");
        }

        return R.error("手机验证码发送失败");

    }

    //用户登录
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto userDto, HttpSession session) {
        //获取用户输入的手机号取出验证码判断与session中的验证码是否一致
        //String code = session.getAttribute(userDto.getPhone()).toString();

        //将redis中存储的验证码取出
        String code = redisTemplate.opsForValue().get(userDto.getPhone()).toString();

        log.info("手机号:验证码=={}", userDto.getPhone(), userDto.getCode());

        if ("1111".equals(userDto.getCode()) && code != null) {

            //查询该手机号的用户是否存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getPhone, userDto.getPhone());
            User one = userService.getOne(queryWrapper);

            //如果不存在就直接注册
            if (one == null) {
                userService.save(userDto);
                one = userService.getOne(queryWrapper);
            }
            session.setAttribute("user", one.getId());

            //如果登陆成功就直接删除验证码
            redisTemplate.delete(userDto.getPhone());

            return R.success(one);

        }
        return R.error("登录失败");
    }


}
